import { getDepositoryPage, getUserPage } from "@/api/common";
import {
  getStoreOrderList,
  getStoreOrderSum,
  upStoreOrderStatus
} from "@/api/order/store";
import { useRouterNavigation } from "@/router/utils";
import { useUserStoreHook } from "@/store/modules/user";
import { dealDataExcept, dealDataRide } from "@/utils/common";
import { message } from "@/utils/message";
import { goodsCodeRend, goodsNameRend } from "@/utils/tableColumns";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection, getKeyList } from "@pureadmin/utils";
import dayjs from "dayjs";
import { ElMessageBox, ElTag } from "element-plus";
import { h, onMounted, reactive, type Ref, ref, watch } from "vue";

// 组件
import { DictTag } from "@/components/common/DictTag";
import { cloneDeep } from "@pureadmin/utils";
import { checkOrderStatus } from "../../orderUtils";

export function useStoreOrder(bizType: number, tableRef?: Ref) {
  const { push } = useRouterNavigation();
  const selectData = ref({
    ckList: [],
    userList: []
  });
  const totalForm = ref<any>({});
  const form = reactive({
    storeIds: useUserStoreHook().loginStoreId,
    bizType: bizType, // 2: 门店端  4: 驻店店长
    storeOrderCode: "",
    goodsCode: "",
    goodsName: "",
    barCode: "",
    specName: "",
    specCode: "",
    storeName: "",
    depositoryId: "",
    status: 999,
    createUserId: "",
    businessDate: [],
    businessDateBegin: "",
    businessDateEnd: "",
    pageNum: 1,
    pageSize: 20
  });
  const currentTreeData = reactive({
    id: null,
    menuName: ""
  });
  // const formRef = ref();
  const dataList = ref([]);
  const loading = ref(false);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [20, 50, 100, 200],
    background: true
  });
  const tabType = ref(999);
  const tabList = ref([
    { label: "全部", name: 999, count: 0 },
    { label: "待审核", name: 0, count: 0 },
    { label: "发货中", name: 1, count: 0 },
    { label: "部分发货", name: 2, count: 0 },
    { label: "已发货", name: 3, count: 0 },
    { label: "已完成", name: 4, count: 0 },
    { label: "已驳回", name: 5, count: 0 },
    { label: "已取消", name: 6, count: 0 },
    { label: "已关闭", name: 7, count: 0 }
  ]);
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      type: "expand",
      slot: "expand",
      fixed: "left",
      width: "30px"
    },
    {
      label: "业务日期",
      prop: "businessDate",
      width: 120,
      align: "left",
      fixed: "left",
      formatter: ({ businessDate }) => dayjs(businessDate).format("YYYY-MM-DD")
    },
    {
      label: "采购订单编码",
      prop: "storeOrderCode",
      align: "left",
      width: 235
    },
    {
      label: "门店名称",
      prop: "storeName",
      width: 170
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 95,
      cellRenderer: ({ row }) => getOrderStatus(row.status)
    },
    {
      label: "订单总金额",
      prop: "totalPrice",
      width: 120,
      formatter: ({ totalPrice }) => dealDataExcept(totalPrice)
    },
    {
      label: "商品总数量",
      prop: "totalCommodities",
      width: 120
    },
    {
      label: "已发货数量",
      prop: "quantityShipped",
      width: 120
    },
    {
      label: "收货仓库",
      prop: "depositoryName",
      minWidth: 120
    },
    {
      label: "创建人",
      prop: "createUserName",
      minWidth: 100
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      minWidth: 140,
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm")
    },
    {
      label: "备注",
      prop: "des",
      minWidth: 120
    },
    {
      label: "操作",
      align: "left",
      fixed: "right",
      width: bizType == 4 ? 145 : 172,
      slot: bizType == 4 ? "masterOperation" : "operation"
    }
  ];

  const childColumns: TableColumnList = [
    {
      label: "商品名称/规格名称",
      prop: "goodsName",
      minWidth: 180,
      align: "left",
      fixed: "left",
      cellRenderer: goodsNameRend
    },
    {
      label: "商品编码/规格编码",
      prop: "goodsCode",
      align: "left",
      minWidth: 170,
      cellRenderer: goodsCodeRend
    },
    {
      label: "商品条码",
      prop: "barCode",
      minWidth: 120,
      formatter: ({ barCode }) => barCode || "--"
    },
    {
      label: "关联供应商",
      prop: "supplierName",
      minWidth: 120,
      formatter: ({ supplierName }) => supplierName || "--"
    },
    {
      label: "提醒",
      prop: "reminderState",
      minWidth: 100,
      cellRenderer: ({ row }) => getRemindStatus(row.reminderState)
    },
    {
      label: "商品类型",
      prop: "goodsType",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <DictTag dict-type="PRODUCT_TYPE" dict-value={row.goodsType} />
      )
    },
    {
      label: "单价",
      prop: "buyPrice",
      minWidth: 100,
      formatter: ({ buyPrice }) => dealDataExcept(buyPrice)
    },
    {
      label: "数量",
      prop: "goodsAmount",
      minWidth: 100
    },
    {
      label: "金额",
      prop: "goodsStatus",
      minWidth: 100,
      formatter: row =>
        dealDataExcept(dealDataRide(row.goodsAmount, row.buyPrice))
    },
    {
      label: "发货仓",
      prop: "deliveryDepositoryName",
      minWidth: 100,
      cellRenderer: ({ row }) =>
        row.depositoryType == 2 ? "供应商仓" : row.deliveryDepositoryName
    }
  ];

  function handleUpdate(row) {
    console.log(row);
  }

  // 获取订单状态 primary success danger
  const getOrderStatus = status => {
    if (status == null) {
      return "--";
    }
    // 	采购订单状态 0 待审核 1 发货中 2部分发货 3 已发货 4 已完成 5 已驳回 6 已取消 7 已关闭
    let statusMap = {
      0: { text: "待审核", type: "warning" },
      1: { text: "发货中", type: "primary" },
      2: { text: "部分发货", type: "primary" },
      3: { text: "已发货", type: "primary" },
      4: { text: "已完成", type: "success" },
      5: { text: "已驳回", type: "danger" },
      6: { text: "已取消", type: "info" },
      7: { text: "已关闭", type: "danger" }
    };
    let obj = statusMap[status];
    if (!obj) {
      return "--";
    }
    return h(
      ElTag,
      {
        type: obj.type
      },
      () => obj.text
    );
  };

  // 获取提醒状态
  const getRemindStatus = status => {
    if (status == null) {
      return "--";
    }
    // 提醒状态 0 待审核 1 发货中 2 待确认 3 已确认 4 配货中 5 部分发货 6 已发货 7 部分入库 8 已入库 9 已关闭
    let statusMap = {
      0: { text: "待审核", type: "primary" },
      1: { text: "发货中", type: "primary" },
      2: { text: "待确认", type: "warning" },
      3: { text: "已确认", type: "primary" },
      4: { text: "配货中", type: "primary" },
      5: { text: "部分发货", type: "success" },
      6: { text: "已发货", type: "success" },
      7: { text: "部分入库", type: "warning" },
      8: { text: "已入库", type: "info" },
      9: { text: "已关闭", type: "danger" },
      10: { text: "已取消", type: "danger" },
      11: { text: "已驳回", type: "danger" }
    };
    let obj = statusMap[status];
    if (!obj) {
      return "--";
    }
    return h(
      ElTag,
      {
        type: obj.type
      },
      () => obj.text
    );
  };

  // 查看商品详情
  const showOrderDetail = row => {
    let detailPath =
      bizType == 4
        ? "/order/store/detail/checkDetail"
        : "/order/store/detail/defaultDetail";
    push({
      path: detailPath,
      query: { id: row.id }
    });
  };

  // 审核状态 1 通过 2驳回 3 取消订单
  const handleOpt = async (row, opt) => {
    // 先判断数据状态是否已经发生变化
    checkOrderStatus(row).then(async isCanNext => {
      if (!isCanNext) {
        // 进行刷新
        console.log("进行刷新");
        onSearch();
        return;
      }

      console.log("进行操作");
      let params = {
        id: row.id,
        auditStatus: opt
      };
      await upStoreOrderStatus(params);
      onSearch();
      message("操作成功", { type: "success" });
    });
  };

  function handleSizeChange(val: number) {
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.pageNum = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量操作 */
  function onBatchStart(goodsStatus) {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const optIds = getKeyList(curSelected, "id");
    console.log("curSelected");
    if (optIds.length <= 0) {
      message("请选择要操作的数据", {
        type: "warning"
      });
    }

    ElMessageBox.confirm(
      `确认要<strong>${goodsStatus == 1 ? "批量启用" : "批量停用"}</strong>选中的商品吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        // await batchUpGoodsStatus({ goodsIds: optIds, goodsStatus });
        tableRef.value.getTableRef().clearSelection();
        onSearch();
        message("操作成功", {
          type: "success"
        });
      })
      .catch(() => {});
  }

  async function onSearch() {
    loading.value = true;

    // 处理请求参数
    let tempForm = { ...form };
    if (tempForm.businessDate && tempForm.businessDate.length > 0) {
      tempForm.businessDateBegin = tempForm.businessDate[0];
      tempForm.businessDateEnd = tempForm.businessDate[1];
    }
    delete tempForm.businessDate;

    tempForm.status = tabType.value;
    if (tempForm.status == 999) delete tempForm.status;

    const { data } = await getStoreOrderList(tempForm).catch(
      () => (loading.value = false)
    );
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;

    // 统计
    delete tempForm.status;
    const sumReq = await getStoreOrderSum(tempForm);
    totalForm.value = sumReq.data || {};
    let countList = sumReq.data?.statisticsResponses || [];
    let total = 0;
    let tempTabList = cloneDeep(tabList.value);
    tempTabList.forEach(v => (v.count = 0));
    countList.forEach(v => {
      tempTabList[v.status + 1].count = v.storeOrderNum || 0;
      total += Number(v.storeOrderNum);
    });
    tempTabList[0].count = total;
    tabList.value = tempTabList;

    setTimeout(() => {
      loading.value = false;
    }, 200);
  }

  watch(tabType, () => {
    onSearch();
  });

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.storeOrderCode = "";
    form.goodsCode = "";
    form.goodsName = "";
    form.barCode = "";
    form.specName = "";
    form.specCode = "";
    form.storeName = "";
    form.depositoryId = "";
    form.status = 999;
    tabType.value = 999;
    form.createUserId = "";
    form.businessDate = [];
    onSearch();
  };

  onMounted(() => {
    onSearch();

    // 获取仓库列表
    let params = {
      type: 0,
      status: 0,
      pageNum: 1,
      pageSize: 500
    };
    getDepositoryPage(params).then(res => {
      selectData.value.ckList = res.data?.records || [];
    });

    // 获取用户列表
    let userParams = {
      bizType: 2,
      enableStatus: 1,
      pageNum: 1,
      pageSize: 500
    };
    getUserPage(userParams).then(res => {
      selectData.value.userList = res.data?.records || [];
    });
  });

  return {
    form,
    loading,
    columns,
    childColumns,
    dataList,
    selectedNum,
    pagination,
    currentTreeData,
    tabType,
    tabList,
    selectData,
    totalForm,
    deviceDetection,
    onSearch,
    resetForm,
    onBatchStart,
    handleUpdate,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    showOrderDetail,
    handleOpt
  };
}
